﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common;

namespace GameServer.Servers
{
    class Message
    {
        //存读取到的数据用的数组
        private byte[] data = new byte[1024];
        //在数组中开始存数据的索引
        //在数组中存取了多少字节的数据
        private int startIndex = 0;

        public byte[] Data
        {
            get { return data; }
        }

        public int StartIndex
        {
            get { return startIndex; }
        }

        /// <summary>
        /// 剩余长度
        /// </summary>
        public int ReaminSize
        {
            get { return data.Length - startIndex; }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="count"></param>
        //public void AddCount(int count)
        //{
        //    startIndex += count;
        //}

        /// <summary>
        /// 读取数据/解析数据
        /// </summary>
        public void ReadMessage(int newDataAmout, Action<RequestCode, ActionCode, string> processDataCallback = null)
        {
            startIndex += newDataAmout;
            while (true)
            {
                //判断最小的数据长度
                if (startIndex <= 4)
                    return;
                //解析数据长度
                int count = BitConverter.ToInt32(data, 0);
                //读取剩余数据
                if ((startIndex - 4) >= count)//当前消息是完整的
                {
                    //string s = Encoding.UTF8.GetString(data, 4, count);
                    //Console.WriteLine("解析出来一条数据:" + s);

                    RequestCode requestCode = (RequestCode)BitConverter.ToInt32(data, 4);
                    ActionCode actionCode = (ActionCode)BitConverter.ToInt32(data, 8);
                    string s = Encoding.UTF8.GetString(data, 12, count - 8);
                    processDataCallback(requestCode, actionCode, s);
                    Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
                    startIndex -= (count + 4);
                }
                else
                {
                    break;
                }
            }
        }

        /// <summary>
        /// 包装数据
        /// 数据长度+requestcode长度+数据
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] PackData(ActionCode actionCode, string data)
        {
            byte[] actionCodeBytes = BitConverter.GetBytes((int)actionCode);
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            int dataAmout = actionCodeBytes.Length + dataBytes.Length;
            byte[] amoutBytes = BitConverter.GetBytes(dataAmout);
            byte[] newBytes = amoutBytes.Concat(actionCodeBytes).ToArray<byte>();
            return newBytes.Concat(dataBytes).ToArray<byte>();
        }
    }
}
